package com.elmcode.server.service.impl;

import com.elmcode.server.elmenum.OrderStatusEnum;
import com.elmcode.server.entity.AddressEntity;
import com.elmcode.server.entity.BookDetailEntity;
import com.elmcode.server.exception.BusException;
import com.elmcode.server.service.AddressService;
import com.elmcode.server.service.BookDetailService;
import com.elmcode.server.service.BookService;
import com.elmcode.server.vo.BookDetailInfoVo;
import com.elmcode.server.vo.BookResqVo;
import com.elmcode.server.vo.BookVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elmcode.common.utils.Query;

import com.elmcode.server.dao.BookDao;
import com.elmcode.server.entity.BookEntity;

@Slf4j
@Service("bookService")
public class BookServiceImpl extends ServiceImpl<BookDao, BookEntity> implements BookService {

    @Autowired
    private AddressService addressService;

    @Autowired
    private BookDetailService bookDetailService;

    @Override
    public BookResqVo queryPage(Map<String, Object> params) {
        QueryWrapper<BookEntity> queryWrapper = new QueryWrapper<>();

        String number = (String) params.get("num");
        if(!StringUtils.isEmpty(number)){
            queryWrapper.eq("num",number);
        }
        String phone = (String) params.get("phone");
        if(!StringUtils.isEmpty(phone)){
            queryWrapper.like("phone",phone);
        }
        //status
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("status",status);
        }

        //TODO 比较时间
        String beginTime = (String) params.get("beginTime");
        String endTime = (String) params.get("endTime");

/*        //当beginTime不为null，endTime为null
        if(!StringUtils.isEmpty(beginTime) && StringUtils.isEmpty(endTime)) {
            queryWrapper.ge("create_time", beginTime);
        }
        //当beginTime为null，endTime不为null
        if(StringUtils.isEmpty(beginTime) && !StringUtils.isEmpty(endTime)){
            queryWrapper.le("create_time",endTime);
        }*/

        //当beginTime和endTime都不为null 的时候
        if(!StringUtils.isEmpty(beginTime) && !StringUtils.isEmpty(endTime)){
            queryWrapper.between("create_time",beginTime,endTime);
        }

        IPage<BookEntity> page = this.page(
                new Query<BookEntity>().getPage(params),
                queryWrapper
        );
        List<BookEntity> entities = page.getRecords();

        /**
         *     private String number;
         *     private String customerName;
         *     private String phone;
         *     private String address;  无
         *     private String amount;
         *     private String createTime;
         *     private Integer status;
         */
        List<BookVo> collect = entities.stream().map(item -> {
            BookVo bookVo = new BookVo();
            BeanUtils.copyProperties(item, bookVo);

            //设置地址：
            AddressEntity address = addressService.getById(item.getAddressId());
            if(address != null){
                bookVo.setAddress(address.getProvinceName() + address.getCityName() + address.getAreaName() + address.getDetail());
            }
            return bookVo;
        }).collect(Collectors.toList());

        BookResqVo bookResqVo = new BookResqVo();
        bookResqVo.setBookVos(collect);
        bookResqVo.setTotal((int) page.getTotal());

        return bookResqVo;
    }

    @Override
    public BookDetailInfoVo getByNum(String num) {

        QueryWrapper<BookEntity> queryWrapper = new QueryWrapper<BookEntity>().eq("num",num);
        BookEntity bookEntity = this.baseMapper.selectOne(queryWrapper);
        if(bookEntity != null){
            BookDetailInfoVo bookDetailInfoVo = new BookDetailInfoVo();
            BeanUtils.copyProperties(bookEntity,bookDetailInfoVo);


            bookDetailInfoVo.setAmount(bookEntity.getAmount());
            bookDetailInfoVo.setPayTime(bookEntity.getPayTime());
            bookDetailInfoVo.setPayMethod(bookEntity.getPayMethod());
            bookDetailInfoVo.setRemark(bookEntity.getRemark());


            //TODO 通过num去查询订单详情
            List<BookDetailEntity> bookDetailEntities = bookDetailService.selectByBookNum(bookEntity.getNum());
            bookDetailInfoVo.setBookDetailVOList(bookDetailEntities);
            return bookDetailInfoVo;
        }else {
            throw new BusException("当前订单编号错误，请处理");
        }
    }

    @Override
    public void receive(String num) {

        synchronized (this){
            BookEntity bookEntity = this.baseMapper.selectOne(new QueryWrapper<BookEntity>().eq("num", num));
            if(bookEntity == null){
                throw new BusException("订单号错误，请检查原因");
            }
            if(OrderStatusEnum.PENDING_CONFIRMED.getCode() == bookEntity.getStatus()){
                //如果当前是待接单的状态,设置为已接单
                bookEntity.setStatus(OrderStatusEnum.RECEIVED.getCode());

                this.baseMapper.updateById(bookEntity);
            }else {
                throw new BusException("当前订单已被接收");
            }
        }

    }

    @Override
    public void reject(String num, String rejectReason) {
        synchronized (this){
            BookEntity bookEntity = this.baseMapper.selectOne(new QueryWrapper<BookEntity>().eq("num", num));
            if(bookEntity == null){
                throw new BusException("订单号错误，请检查原因");
            }
            if(OrderStatusEnum.PENDING_CONFIRMED.getCode() == bookEntity.getStatus()){
                //如果当前是待接单的状态,设置为拒单
                bookEntity.setStatus(OrderStatusEnum.CANCELLED.getCode());
                bookEntity.setRejectionReason(rejectReason);

                bookEntity.setCancelTime(new Date());

                this.baseMapper.updateById(bookEntity);
            }else {
                throw new BusException("当前订单已被取消");
            }
        }
    }

    @Override
    public void delivery(String num) {
        synchronized (this){
            BookEntity bookEntity = this.baseMapper.selectOne(new QueryWrapper<BookEntity>().eq("num", num));
            if(bookEntity == null){
                throw new BusException("订单号错误，请检查原因");
            }
            if(OrderStatusEnum.RECEIVED.getCode() == bookEntity.getStatus()){
                //如果当前是待接单的状态,设置为已接单
                bookEntity.setStatus(OrderStatusEnum.DELIVERING.getCode());
                bookEntity.setDeliveryTime(new Date());
                this.baseMapper.updateById(bookEntity);
            }else {
                throw new BusException("当前订单已被派送");
            }
        }
    }

    @Override
    public void complete(String num) {
        synchronized (this){
            BookEntity bookEntity = this.baseMapper.selectOne(new QueryWrapper<BookEntity>().eq("num", num));
            if(bookEntity == null){
                throw new BusException("订单号错误，请检查原因");
            }
            if(OrderStatusEnum.DELIVERING.getCode() == bookEntity.getStatus()){
                //如果当前是待接单的状态,设置为已接单
                bookEntity.setStatus(OrderStatusEnum.COMPLETED.getCode());
                bookEntity.setDeliveryTime(new Date());

                this.baseMapper.updateById(bookEntity);
            }else {
                throw new BusException("当前订单已完成");
            }
        }
    }

    @Override
    public void updateByNum(BookEntity order) {
        QueryWrapper<BookEntity> queryWrapper = new QueryWrapper<BookEntity>().eq("num",order.getNum());
        this.update(order,queryWrapper);
    }

    @Override
    public BookEntity getOrderByNum(String num) {
        QueryWrapper<BookEntity> queryWrapper = new QueryWrapper<BookEntity>().eq("num",num);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<BookEntity> orderCancel() {
        //TODO 查找当前所有 处于待支付的订单  并且  已经超时  的订单

        Date curDate = new Date();//当前时间

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,-30); //10:30
        Date startDate = calendar.getTime();//当前时间 - 30分钟之后 的时间

        log.info("当前时间：{}",curDate);
        log.info("30分钟之前的时间：{}",startDate);

        //创建时间 <= 30分钟之前的时间 startDate
        QueryWrapper<BookEntity> queryWrapper = new QueryWrapper<BookEntity>()
                .eq("status", OrderStatusEnum.PENDING_PAYMENT.getCode())
                .lt("create_time",startDate);

        return this.baseMapper.selectList(queryWrapper);
    }

}